/*
   Copyright (c) 2011 Mizar Tools Contributors (mizartools.org)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/*  Contributors :
 *	2011-04-11 Marco Riccardi - initial implementation
 *  
 */
package org.mizartools.example.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.mizartools.system.Article;
import org.mizartools.system.ArticleFactory;
import org.mizartools.system.EnvironFile;
import org.mizartools.system.ListArticleFile;
import org.mizartools.system.executable.AbstractExecutableFile;
import org.mizartools.system.executable.Accommodator;
import org.mizartools.system.executable.ExecutableException;
import org.mizartools.system.executable.InaccessibleItemsDetector;
import org.mizartools.system.executable.IrrelevantInferencesDetector;
import org.mizartools.system.executable.IrrelevantIterativeStepsDetector;
import org.mizartools.system.executable.IrrelevantLabelDetector;
import org.mizartools.system.executable.IrrelevantPremisesDetector;
import org.mizartools.system.executable.IrrelevantTheoremsSchemesDetector;
import org.mizartools.system.executable.IrrelevantVocabularyDetector;
import org.mizartools.system.executable.TrivialProofsDetector;
import org.mizartools.utility.TemporaryDirectory;
import org.mizartools.utility.TemporaryDirectoryException;
import org.mizartools.utility.TemporaryDirectoryFactory;
import org.mizartools.utility.UtilityFile;

@SuppressWarnings("serial")
public class TestIrrelevantUtilitiesPanel extends JPanel {

	private JTextArea textArea;
	private JScrollPane scroller;
	private JPanel northPanel;
	private JPanel checkBoxPanel;
	private JCheckBox checkBoxInaccessibleItems;
	private JCheckBox checkBoxIrrelevantInferences;
	private JCheckBox checkBoxIrrelevantIterativeSteps;
	private JCheckBox checkBoxIrrelevantLabel;
	private JCheckBox checkBoxIrrelevantPremises;
	private JCheckBox checkBoxIrrelevantTheoremsSchemes;
	private JCheckBox checkBoxIrrelevantVocabulary;
	private JCheckBox checkBoxTrivialProofs;
	private JButton button;
	
	private JPanel progressBarPanel;
	private JProgressBar progressBarMML;
	private JProgressBar progressBarExecutable;
	private TestFrame testFrame;

	public TestIrrelevantUtilitiesPanel(TestFrame testFrame){
		super();
		this.testFrame = testFrame;
    	setLayout(new BorderLayout());
		setPreferredSize(new Dimension(500, 150));
		
		northPanel = new JPanel();
		northPanel.setLayout(new BorderLayout());

		
		button = new JButton();
		AbstractAction action =  new AbstractAction() { 
	 	    public void actionPerformed(ActionEvent e) {
	 	    	textArea.setText(Calendar.getInstance().getTime().toString()+"\n\n");
	 	    	TestIrrelevantUtilitiesPanel.Job job = new TestIrrelevantUtilitiesPanel.Job();
	 			Thread thread = new Thread(job);
	 			thread.start();
	 	    } 
	 	}; 
	 	button.setAction(action);
	 	button.setMaximumSize(getMaximumSize());
	 	button.setText("Start");
	 	northPanel.add(button, BorderLayout.NORTH);
		
		checkBoxPanel = new JPanel();
		checkBoxPanel.setLayout(new FlowLayout());
		checkBoxPanel.setPreferredSize(new Dimension(500, 35));

		checkBoxTrivialProofs = new JCheckBox("Trivial Proofs");
		checkBoxTrivialProofs.setSelected(true);
		checkBoxPanel.add(checkBoxTrivialProofs, FlowLayout.LEFT);
		checkBoxIrrelevantVocabulary = new JCheckBox("Vocabulary");
		checkBoxIrrelevantVocabulary.setSelected(true);
		checkBoxPanel.add(checkBoxIrrelevantVocabulary, FlowLayout.LEFT);
		checkBoxIrrelevantTheoremsSchemes = new JCheckBox("Theorems & Schemes");
		checkBoxIrrelevantTheoremsSchemes.setSelected(true);
		checkBoxPanel.add(checkBoxIrrelevantTheoremsSchemes, FlowLayout.LEFT);
		checkBoxIrrelevantPremises = new JCheckBox("Premises");
		checkBoxIrrelevantPremises.setSelected(true);
		checkBoxPanel.add(checkBoxIrrelevantPremises, FlowLayout.LEFT);
		checkBoxIrrelevantLabel = new JCheckBox("Label");
		checkBoxIrrelevantLabel.setSelected(true);
		checkBoxPanel.add(checkBoxIrrelevantLabel, FlowLayout.LEFT);
		checkBoxIrrelevantIterativeSteps = new JCheckBox("Iterative Steps");
		checkBoxIrrelevantIterativeSteps.setSelected(true);
		checkBoxPanel.add(checkBoxIrrelevantIterativeSteps, FlowLayout.LEFT);
		checkBoxIrrelevantInferences = new JCheckBox("Inferences");
		checkBoxIrrelevantInferences.setSelected(true);
		checkBoxPanel.add(checkBoxIrrelevantInferences, FlowLayout.LEFT);
		checkBoxInaccessibleItems = new JCheckBox("Inaccessible Items");
		checkBoxInaccessibleItems.setSelected(true);
		checkBoxPanel.add(checkBoxInaccessibleItems, FlowLayout.LEFT);

	 	northPanel.add(checkBoxPanel, BorderLayout.SOUTH);
		
		add(northPanel, BorderLayout.NORTH);
		
		textArea = new JTextArea();
		textArea.setEditable(false);
        scroller = new JScrollPane();
		scroller.getViewport().add(textArea);
		add(scroller, BorderLayout.CENTER);
		
		progressBarPanel = new JPanel();
		progressBarPanel.setLayout(new BorderLayout());
		progressBarExecutable = new JProgressBar();
		progressBarPanel.add(progressBarExecutable, BorderLayout.NORTH);
		progressBarMML = new JProgressBar();
		progressBarPanel.add(progressBarMML, BorderLayout.SOUTH);
		add(progressBarPanel,BorderLayout.SOUTH);
	}
	
	private class Job implements Runnable {

		private String mmlPath = EnvironFile.getMIZFILES() + File.separator + "mml";
		
		@Override
		public void run() {
			button.setEnabled(false);
			TemporaryDirectory temporaryDirectory = null;
			long beforeTime = Calendar.getInstance().getTimeInMillis() - 24*60*60*1000;
			TemporaryDirectoryFactory.clearTemporaryDirectories(beforeTime);
			try {
				temporaryDirectory = TemporaryDirectoryFactory.newTemporaryDirectory();
			} catch (TemporaryDirectoryException e) {
				textArea.append(e.getMessage());
			}
			if (temporaryDirectory == null){
	    		textArea.append("\n");
	    		textArea.repaint();
	    		textArea.setCaretPosition(textArea.getText().length()-1);
	    		return;
			}
			File workDirectory = temporaryDirectory.getFile();
			textArea.append("Temporary Directory : " + workDirectory.getPath());
			textArea.append("\n");
			textArea.repaint();
			textArea.setCaretPosition(textArea.getText().length()-1);
			LinkedList<String> articleList = ListArticleFile.getArticleList();
	    	progressBarMML.setMaximum(articleList.size()+1);
	    	progressBarMML.setValue(0);
	    	progressBarMML.setIndeterminate(false);
	    	progressBarExecutable.setMaximum(100);
	    	progressBarExecutable.setValue(0);
			progressBarExecutable.setIndeterminate(false);
	    	Article article = null;
	    	String articleName = null;
	    	String fileName = null;
	    	int progress = 0;
			try {
				boolean error = false;
		    	for (String aid : articleList){
		    		if (!error){
		    			temporaryDirectory.clear();
			    		article = ArticleFactory.getInstance().getArticle(aid);
			    		articleName = article.getAid().toLowerCase();
						textArea.append((articleName+"        ").substring(0,10)+" : ");
			    		textArea.repaint();
			    		textArea.setCaretPosition(textArea.getText().length()-1);
						File sourceFile = new File(mmlPath, articleName+".miz");
						File destinationFile = new File(workDirectory, articleName+".miz");
						error = !UtilityFile.Copy(sourceFile, destinationFile);
						AbstractExecutableFile abstractExecutableFile;
						if (!error){
							Accommodator accomodator = new Accommodator(temporaryDirectory, destinationFile.getName());
							error = check("[Acc] ", accomodator, 50);
						}						
						if (!error && checkBoxInaccessibleItems.isSelected()){
							abstractExecutableFile = new InaccessibleItemsDetector(temporaryDirectory, destinationFile.getName());
							error = check("[InacItem] ", abstractExecutableFile, 50);
						}
						if (!error && checkBoxIrrelevantInferences.isSelected()){
							abstractExecutableFile = new IrrelevantInferencesDetector(temporaryDirectory, destinationFile.getName());
							error = check("[Infe] ", abstractExecutableFile, 250);
						}
						if (!error && checkBoxIrrelevantIterativeSteps.isSelected()){
							abstractExecutableFile = new IrrelevantIterativeStepsDetector(temporaryDirectory, destinationFile.getName());
							error = check("[Iter] ", abstractExecutableFile, 250);
						}
						if (!error && checkBoxIrrelevantLabel.isSelected()){
							abstractExecutableFile = new IrrelevantLabelDetector(temporaryDirectory, destinationFile.getName());
							error = check("[Label] ", abstractExecutableFile, 50);
						}
						if (!error && checkBoxIrrelevantPremises.isSelected()){
							abstractExecutableFile = new IrrelevantPremisesDetector(temporaryDirectory, destinationFile.getName());
							error = check("[Prem] ", abstractExecutableFile, 250);
						}
						if (!error && checkBoxIrrelevantTheoremsSchemes.isSelected()){
							abstractExecutableFile = new IrrelevantTheoremsSchemesDetector(temporaryDirectory, destinationFile.getName());
							error = check("[ThSch] ", abstractExecutableFile, 50);
						}
						if (!error && checkBoxIrrelevantVocabulary.isSelected()){
							abstractExecutableFile = new IrrelevantVocabularyDetector(temporaryDirectory, destinationFile.getName());
							error = check("[Voc] ", abstractExecutableFile, 50);
						}
						if (!error && checkBoxTrivialProofs.isSelected()){
							abstractExecutableFile = new TrivialProofsDetector(temporaryDirectory, destinationFile.getName());
							error = check("[TriPro] ", abstractExecutableFile, 50);
						}
						
			    		textArea.append("\n");
			    		textArea.repaint();
			    		textArea.setCaretPosition(textArea.getText().length()-1);
				    	progressBarMML.setValue(progress++);
				    	progressBarMML.repaint();
				    	if (testFrame.isClosed()) {
				    		error = true;
				    	}
		    		}
		    	}
			} 
			catch (Exception e) {
				textArea.append("\n");
	    		textArea.append(fileName);
	    		textArea.append(" -> Error");
				textArea.append("\n");
				textArea.append(e.getMessage());
				textArea.append("\n");
	    		textArea.repaint();
	    		textArea.setCaretPosition(textArea.getText().length()-1);
			}
			textArea.append("\n");
			textArea.repaint();
			textArea.setCaretPosition(textArea.getText().length()-1);
	    	progressBarMML.setValue(0);
			button.setEnabled(true);
		}
		
	}

	private boolean check(String text, AbstractExecutableFile abstractExecutableFile, int sleepTime) {
		boolean error = false;
		long duration;
		textArea.append(text);
		textArea.repaint();
		textArea.setCaretPosition(textArea.getText().length()-1);
		progressBarExecutable.setValue(0);
		duration = Calendar.getInstance().getTimeInMillis();
		try {
			abstractExecutableFile.start();
			while (abstractExecutableFile.isExecuting()) {
				Thread.sleep(sleepTime);
		    	progressBarExecutable.setValue(abstractExecutableFile.getPercentage());
			}
			if (abstractExecutableFile.getExitValue() != 0) {
				error = true;
				textArea.append("Error exit value = " + abstractExecutableFile.getExitValue());
				textArea.append("\n");
			}
			if (abstractExecutableFile.getException() != null) {
				error = true;
				textArea.append(abstractExecutableFile.getException().getMessage());
				textArea.append("\n");
			}
		} catch (ExecutableException e) {
			error = true;
			textArea.append(e.getMessage());
			textArea.append("\n");
		} catch (InterruptedException e) {
			error = true;
			textArea.append(e.getMessage());
			textArea.append("\n");
		}
		duration = Calendar.getInstance().getTimeInMillis() - duration;
		textArea.append("["+((double)duration)/1000+"] ");
		textArea.repaint();
		textArea.setCaretPosition(textArea.getText().length()-1);
		return error;
	}
	
	
	
}
